<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
/**
 * 评审专业维护
 *
 * @icon fa fa-circle-o
 */
class Major extends Backend
{

    /**
     * Major模型对象
     * @var \app\admin\model\pt\Major
     */
    protected $model = null;

    protected $excludeFields = ['update_time'];

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\admin\model\pt\Major;
        $seriesList = $this->model::where('parent_id', 0)->column('major_name', 'id');
        $this->view->assign('seriesList', $seriesList);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        // 获取筛选条件
        $seriesId = $this->request->get('series_id', 1);


        // 如果选择了特定系列，只查询该系列及其子级数据
        // 先获取该系列下的所有类别ID
        $categoryIds = $this->model::where('parent_id', $seriesId)->column('id');

        $ruleList = $this->model::field('*,parent_id as pid')
            ->where(function ($query) use ($seriesId, $categoryIds) {
                $query->where('id', $seriesId)  // 系列本身
                    ->whereOr('parent_id', $seriesId);  // 该系列的类别
    
                // 只有当类别ID存在时才添加专业查询条件
                if (!empty($categoryIds)) {
                    $query->whereOr('parent_id', 'in', $categoryIds);  // 该系列类别下的专业
                }
            })
            ->order('parent_id ASC, id ASC')
            ->select();


        // 构建层级结构数据
        $seriesList = []; // 系列列表
        $categoryList = []; // 类别列表  
        $majorList = []; // 专业列表

        foreach ($ruleList as $k => &$v) {
            $v['name'] = $v['major_name'];
            unset($ruleList[$k]['parent_id']);

            // 根据parent_id判断层级
            if ($v['pid'] == 0) {
                // 第一级：职称系列
                $v['type'] = 'series';
                $v['level'] = 1;
                $seriesList[] = $v;
            } else {
                // 查询父级记录来判断层级
                $parent = $this->model::where('id', $v['pid'])->find();
                if ($parent && $parent['parent_id'] == 0) {
                    // 第二级：职称类别
                    $v['type'] = 'category';
                    $v['level'] = 2;
                    $v['series_id'] = $v['pid'];
                    $categoryList[] = $v;
                } else {
                    // 第三级：评审专业
                    $v['type'] = 'major';
                    $v['level'] = 3;
                    $v['category_id'] = $v['pid'];
                    $majorList[] = $v;
                }
            }
        }

        // 构建正确的树形结构：系列 -> 类别 -> 专业
        $rulelistTree = [];

        // 按系列分组，每个系列下包含其类别，每个类别下包含其专业
        foreach ($seriesList as $series) {
            // 添加系列
            $series['name'] = '【系列】' . $series['name'];
            $series['haschild'] = 1; // 系列有子节点
            $series['pid'] = 0; // 系列没有父级
            $rulelistTree[] = $series;

            // 添加该系列下的类别
            foreach ($categoryList as $category) {
                if ($category['series_id'] == $series['id']) {
                    $category['name'] = '　【类别】' . $category['name'];
                    $category['haschild'] = 1; // 类别有子节点
                    $category['pid'] = $series['id']; // 类别的父级是系列
                    $rulelistTree[] = $category;

                    // 添加该类别下的专业
                    foreach ($majorList as $major) {
                        if ($major['category_id'] == $category['id']) {
                            $major['name'] = '　　　' . $major['name'];
                            $major['haschild'] = 0; // 专业没有子节点
                            $major['pid'] = $category['id']; // 专业的父级是类别
                            $rulelistTree[] = $major;
                        }
                    }
                }
            }
        }

        $result = array("total" => count($rulelistTree), "rows" => $rulelistTree);
        return json($result);
    }



    /**
     * 读取省市区数据,联动列表
     */
    public function major()
    {
        // 获取cxselect插件传递的参数
        $series = $this->request->get('series');
        $category = $this->request->get('category');
        $where = [];
        $where['parent_id'] = -1;
        // 根据传入参数确定查询条件
        if ($series == null) {
            // 查询职称系列
            $where['parent_id'] = '0';
        } else {
            if ($category == null) {
                $where['parent_id'] = $series;
            } else {
                $where['parent_id'] = $category;
            }

        }

        $majorlist = Db::name('pt_major')->where($where)->field('id as value,major_name as name')->select();
        $this->success('', '', $majorlist);
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        // 前端已经通过联动选择器自动设置了parent_id，这里不需要额外处理

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (\think\exception\ValidateException | \PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
